package com.wxb.qd.utils;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxb.qd.common.PageResult;
import com.wxb.qd.dto.CurrentPage;
import com.wxb.qd.entity.Aerodata;
import com.wxb.qd.entity.Announcement;
import com.wxb.qd.entity.User;
import com.wxb.qd.service.AerodataService;
import com.wxb.qd.service.AnnouncementService;
import com.wxb.qd.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 缓存预热
 * @author wangxb
 */
@Component
@Slf4j
public class PreHeating {

    @Resource
    private RedissonClient redissonClient;


    @Resource
    private  RedisTemplate<String,Object> redisTemplate;
    @Resource
    private UserService userService;

    @Resource
    private AerodataService aerodataService;

    @Resource
    private AnnouncementService announcementService;


    /**
     * 预热一下AeroData；
     * 将该方法设置为每天的凌晨 2点进行，依次是秒分时日月年
     *
     */
    @Scheduled(cron = " 0 0 2 * * *")
//    @Bean
    public void PreCacheAeroData(){
        RLock lock = redissonClient.getLock("wxb:preCache:lock");
        try{
            if (lock.tryLock(0,-1, TimeUnit.MILLISECONDS)){
                System.out.println("getLock:" + Thread.currentThread().getId());
                QueryWrapper<Aerodata> queryWrapper= new QueryWrapper<>();
                queryWrapper.eq("isDelete",0);
                queryWrapper.eq("isShare",1);
                Page<Aerodata> page = aerodataService.page(new Page<>(1, 10),queryWrapper);
                ValueOperations<String, Object> operations = redisTemplate.opsForValue();
                String key = "wxb:qd:aerodata";
                try{
                    operations.set(key,page);
                }catch (Exception e){
                    log.error("将数据加载到缓存出错：" ,e);
                }
                List<Announcement> announcementList = announcementService.list();
                String Annkey = "wxb:qd:announcement";
                try{
                    operations.set(Annkey,announcementList,30,TimeUnit.DAYS);
                }catch (Exception e){
                    log.error("将数据加载到缓存出错：" ,e);
                }
            }
        }catch (Exception e){
            log.error("缓存预热出错 : " ,e);
        }finally {
            if (lock.isHeldByCurrentThread()){
                System.out.println("unlock:"+Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }

}
